/*!
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {customer} from "@mall/api-services";
import * as _ from "lodash";
import * as React from "react";
import {RouteComponentProps, withRouter} from "react-router";
import Button from "../components/button";
import Form, {FormObject} from "../components/form";
import NavBar from "../components/navbar";
import Icon from "../icon";
import ShippingAddressForm from "./shipping-address-form";

import "./shipping-address-new.scss";

interface DeliveryAddressNewProps extends RouteComponentProps {

}

class ShippingAddressNew extends React.Component<DeliveryAddressNewProps> {

    private form: FormObject = Form.createForm('edit-d-a');

    public render() {

        const {history} = this.props;

        return (
            <div className="delivery-address-new">
                <NavBar left={<Icon onClick={() => history.goBack()}
                                    type="left"/>}
                        right={<Button
                            onClick={this.handleSaveDeliveryAddress}
                            type="link">保存</Button>}>新增收货地址</NavBar>
                <ShippingAddressForm form={this.form}/>
            </div>
        );
    }

    private readonly handleSaveDeliveryAddress = () => {
        const {match, history} = this.props;
        const customerId = match.params['customer_id'];
        const deliveryAddress = _.assign(new customer.CustomerAddress(), this.form.getFieldsValue());
        customer.CustomerAddressServiceV1
            .addAddress(customerId, deliveryAddress)
            .then(() => history.goBack());
    };
}

export default withRouter(ShippingAddressNew);
